package com.zhentao.dataintegrity.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.dataintegrity.domain.entity.SubtaskDetail;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface SubtaskDetailMapper extends BaseMapper<SubtaskDetail> {

    /**
     * 分页查询子任务详情
     */
    @Select("<script>" +
            "SELECT * FROM di_subtask_detail " +
            "WHERE execution_id = #{executionId} " +
            "<if test='dataTypeCode != null and dataTypeCode != \"\"'> AND data_type_code = #{dataTypeCode} </if>" +
            "<if test='executionStatus != null and executionStatus != \"\"'> AND execution_status = #{executionStatus} </if>" +
            "ORDER BY start_time DESC" +
            "</script>")
    IPage<SubtaskDetail> selectPageByExecutionId(Page<SubtaskDetail> page,
                                               @Param("executionId") String executionId,
                                               @Param("dataTypeCode") String dataTypeCode,
                                               @Param("executionStatus") String executionStatus);

    /**
     * 根据执行ID查询子任务详情
     */
    @Select("SELECT * FROM di_subtask_detail " +
            "WHERE execution_id = #{executionId} " +
            "ORDER BY start_time")
    List<SubtaskDetail> selectByExecutionId(@Param("executionId") String executionId);

    /**
     * 根据任务ID查询子任务详情
     */
    @Select("SELECT * FROM di_subtask_detail " +
            "WHERE task_id = #{taskId} " +
            "ORDER BY start_time DESC " +
            "LIMIT #{limit}")
    List<SubtaskDetail> selectByTaskId(@Param("taskId") Long taskId, @Param("limit") int limit);

    /**
     * 更新子任务状态
     */
    @Update("UPDATE di_subtask_detail SET " +
            "execution_status = #{status}, " +
            "end_time = #{endTime}, " +
            "original_count = #{originalCount}, " +
            "processed_count = #{processedCount}, " +
            "original_rmb_amount = #{originalRmbAmount}, " +
            "processed_rmb_amount = #{processedRmbAmount}, " +
            "original_usd_amount = #{originalUsdAmount}, " +
            "processed_usd_amount = #{processedUsdAmount}, " +
            "diff_rmb_amount = #{diffRmbAmount}, " +
            "diff_usd_amount = #{diffUsdAmount}, " +
            "error_message = #{errorMessage}, " +
            "check_details = #{checkDetails} " +
            "WHERE id = #{id}")
    int updateSubtaskResult(@Param("id") Long id,
                          @Param("status") String status,
                          @Param("endTime") LocalDateTime endTime,
                          @Param("originalCount") Long originalCount,
                          @Param("processedCount") Long processedCount,
                          @Param("originalRmbAmount") BigDecimal originalRmbAmount,
                          @Param("processedRmbAmount") BigDecimal processedRmbAmount,
                          @Param("originalUsdAmount") BigDecimal originalUsdAmount,
                          @Param("processedUsdAmount") BigDecimal processedUsdAmount,
                          @Param("diffRmbAmount") BigDecimal diffRmbAmount,
                          @Param("diffUsdAmount") BigDecimal diffUsdAmount,
                          @Param("errorMessage") String errorMessage,
                          @Param("checkDetails") String checkDetails);

    /**
     * 统计执行结果
     */
    @Select("SELECT " +
            "execution_id, " +
            "SUM(diff_rmb_amount) as total_diff_rmb, " +
            "SUM(diff_usd_amount) as total_diff_usd, " +
            "COUNT(*) as total_subtasks, " +
            "SUM(CASE WHEN execution_status = 'SUCCESS' THEN 1 ELSE 0 END) as success_subtasks, " +
            "SUM(CASE WHEN execution_status = 'FAILED' THEN 1 ELSE 0 END) as failed_subtasks " +
            "FROM di_subtask_detail " +
            "WHERE execution_id = #{executionId} " +
            "GROUP BY execution_id")
    SubtaskDetail getExecutionSummary(@Param("executionId") String executionId);

    /**
     * 查询数据类型统计
     */
    @Select("SELECT " +
            "data_type_code, " +
            "data_type, " +
            "COUNT(*) as execution_count, " +
            "SUM(diff_rmb_amount) as total_diff_rmb, " +
            "SUM(diff_usd_amount) as total_diff_usd " +
            "FROM di_subtask_detail " +
            "WHERE task_id = #{taskId} " +
            "AND start_time >= #{startDate} " +
            "GROUP BY data_type_code, data_type " +
            "ORDER BY total_diff_rmb DESC")
    List<SubtaskDetail> getDataTypeStatistics(@Param("taskId") Long taskId, @Param("startDate") LocalDateTime startDate);

    /**
     * 清理历史详情记录
     */
    @Update("DELETE FROM di_subtask_detail WHERE created_time < #{beforeDate}")
    int cleanDetailsBefore(@Param("beforeDate") LocalDateTime beforeDate);
}
